import { Tab, TabList, Tabs } from "@renderer/components/business/setting-tabs";
import { useSidebar } from "@renderer/components/ui/base/sidebar";
import { useSettingsFocus } from "@renderer/hooks/use-settings-focus";
import { motion } from "motion/react";
import { type RefObject, useEffect, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import { Route, Routes, useLocation, useNavigate } from "react-router-dom";
import { AboutSettings } from "./about-settings";
import { DataSettings } from "./data-settings";
import { GeneralSettings } from "./general-settings";
import { LogViewer } from "./log-viewer";
import { McpSettings } from "./mcp-settings";
import { ModelSettings } from "./model-settings";
import { PreferenceSettings } from "./preference-settings";
import { ShortcutsSettings } from "./shortcuts-settings";

export function SettingsPage() {
  const { t } = useTranslation("translation", {
    keyPrefix: "settings",
  });
  const navigate = useNavigate();
  const location = useLocation();
  const { setSettingsMode } = useSidebar();
  const tabsRef = useRef<HTMLDivElement | null>(null);

  // Focus management for settings tabs - similar to chat input focus
  useSettingsFocus(tabsRef);

  const settingTabs = useMemo(
    () => [
      {
        name: "general-settings",
        path: "/settings/general-settings",
        label: t("general-settings.name"),
      },
      {
        name: "preference-settings",
        path: "/settings/preference-settings",
        label: t("preference-settings.name"),
      },
      {
        name: "model-settings",
        path: "/settings/model-settings",
        label: t("model-settings.name"),
      },
      {
        name: "mcp-settings",
        path: "/settings/mcp-settings",
        label: t("mcp-settings.name"),
      },
      {
        name: "data-settings",
        path: "/settings/data-settings",
        label: t("data-settings.name"),
      },
      {
        name: "shortcuts-settings",
        path: "/settings/shortcuts-settings",
        label: t("shortcuts-settings.name"),
      },
      {
        name: "about-settings",
        path: "/settings/about-settings",
        label: t("about-settings.name"),
      },
    ],
    [t],
  );

  const selectedTabKey = () => {
    // Don't highlight any tab for log viewer (hidden route)
    if (location.pathname.includes("log-viewer")) {
      return "";
    }

    const currentTab = settingTabs.find((tab) =>
      location.pathname.includes(tab.name),
    );
    return currentTab?.name || settingTabs[0].name;
  };

  const handleTabSelect = (key: React.Key) => {
    const tab = settingTabs.find((tab) => tab.name === key);
    if (tab) {
      navigate(tab.path);
    }
  };

  useEffect(() => {
    // Enter settings mode to hide sidebar without animation
    setSettingsMode(true);

    return () => {
      // Exit settings mode to restore original sidebar state
      setSettingsMode(false);
    };
  }, [setSettingsMode]);

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.5 }}
      className="flex h-full flex-row"
    >
      <Tabs
        ref={tabsRef as RefObject<HTMLDivElement>}
        className="w-auto min-w-[var(--setting-width)] justify-end bg-setting"
        orientation="vertical"
        aria-label="Setting Tabs"
        onSelectionChange={handleTabSelect}
        selectedKey={selectedTabKey()}
      >
        <div className="flex w-full justify-end p-3">
          <TabList
            className="w-full gap-y-1 border-none"
            aria-label="Setting Tab List"
            items={settingTabs}
          >
            {(tab) => (
              <Tab
                className="rounded-lg transition-none"
                key={tab.name}
                id={tab.name}
              >
                <span className="w-full text-right">{tab.label}</span>
              </Tab>
            )}
          </TabList>
        </div>
      </Tabs>

      <div className="flex-1 overflow-hidden overflow-y-auto">
        <Routes>
          <Route path="/general-settings" element={<GeneralSettings />} />
          <Route path="/preference-settings" element={<PreferenceSettings />} />
          <Route path="/model-settings" element={<ModelSettings />} />
          <Route path="/mcp-settings/*" element={<McpSettings />} />
          <Route path="/data-settings" element={<DataSettings />} />
          <Route path="/shortcuts-settings" element={<ShortcutsSettings />} />
          <Route path="/about-settings" element={<AboutSettings />} />
          <Route path="/log-viewer" element={<LogViewer />} />
        </Routes>
      </div>
    </motion.div>
  );
}
